package tr.edu.metu.is.mega.client.course.activity;

import java.util.ArrayList;
import java.util.List;

import tr.edu.metu.is.mega.client.core.AsyncCallbackAdapter;
import tr.edu.metu.is.mega.client.core.DownloadHelper;
import tr.edu.metu.is.mega.client.core.MegaUtil;
import tr.edu.metu.is.mega.client.resource.MEGAIconBundle;
import tr.edu.metu.is.mega.client.resource.MEGAResourceBundle;
import tr.edu.metu.is.mega.client.resource.MEGAResources;
import tr.edu.metu.is.mega.client.resource.MegaConstants;
import tr.edu.metu.is.mega.client.service.GwtSubmissionViewService;
import tr.edu.metu.is.mega.common.dto.SubmissionRevisionDTO;

import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.dnd.GridDragSource;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.AbstractImagePrototype;

/**
 * Container to manage course activities
 */
public class SubmissionRevisionDialog extends Window {

    private MEGAResourceBundle resourceBundle;

    private MEGAIconBundle iconBundle;

    private Grid<BeanModel> grid;

    private BeanModelFactory beanModelFactory;

    private final int activityid;

    private final int teamid;

    /**
     * Default constructor.
     */
    public SubmissionRevisionDialog(int activityid, int teamid) {
        this.activityid = activityid;
        this.teamid = teamid;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onRender(Element parent, int pos) {
        super.onRender(parent, pos);
        resourceBundle = MEGAResources.RESOURCEBUNDLE;
        iconBundle = MEGAResources.ICONBUNDLE;
        beanModelFactory = BeanModelLookup.get().getFactory(SubmissionRevisionDTO.class);
        setHeading("Submission Revisions");
        setSize(500, 500);
        setLayout(new FitLayout());
        setModal(true);
        ContentPanel panel = new ContentPanel();
        panel.setHeaderVisible(false);
        panel.setLayout(new FitLayout());

        panel.add(getGrid());
        panel.setTopComponent(getToolBar());
        add(panel);

        Button saveButton = new Button("Ok");
        saveButton.addSelectionListener(new SelectionListener<ButtonEvent>() {

            @Override
            public void componentSelected(ButtonEvent ce) {
                hide();
            }
        });
        panel.addButton(saveButton);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void afterRender() {
        super.afterRender();
        GwtSubmissionViewService.Util.getInstance().getRevisions(activityid, teamid, new AsyncCallbackAdapter<List<SubmissionRevisionDTO>>() {

            @Override
            public void onSuccess(List<SubmissionRevisionDTO> result) {
                setActivities(result);
            }
        });
    }

    /**
     * Initializes and returns toolbar.
     * 
     * @return toolbar
     */
    private ToolBar getToolBar() {
        ToolBar toolBar = new ToolBar();
        toolBar.setMinButtonWidth(70);
        toolBar.setSpacing(5);

        Button downloadSubmissionButton = new Button(resourceBundle.downloadSubmission(), AbstractImagePrototype.create(iconBundle.download()));
        downloadSubmissionButton.addSelectionListener(new SelectionListener<ButtonEvent>() {

            @Override
            public void componentSelected(ButtonEvent ce) {
                if (grid.getSelectionModel().getSelectedItem() != null) {
                    SubmissionRevisionDTO dto = grid.getSelectionModel().getSelectedItem().getBean();
                    DownloadHelper.downloadFile(MegaConstants.TEAM_PATH + dto.getTeamid() + "/submission/" + dto.getFilePath());
                }
            }
        });
        toolBar.add(downloadSubmissionButton);
        return toolBar;
    }

    /**
     * Returns activity grid.
     * 
     * @return grid
     */
    private Grid<BeanModel> getGrid() {
        if (grid == null) {

            ListStore<BeanModel> store = new ListStore<BeanModel>();
            List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
            columns.add(new ColumnConfig(SubmissionRevisionDTO.FIELD_SUBMITTEDBY, "Submitted By", 150));
            ColumnConfig columnConfig = new ColumnConfig(SubmissionRevisionDTO.FIELD_SUBMISSIONDATE, "Submission Date", 150);
            columnConfig.setRenderer(MegaUtil.getDateRenderer(MegaUtil.LONG_DATE_STYLE));
            columns.add(columnConfig);
            columnConfig = new ColumnConfig(SubmissionRevisionDTO.FIELD_FILEPATH, "File", 150);
            columns.add(columnConfig);

            ColumnModel cm = new ColumnModel(columns);

            grid = new Grid<BeanModel>(store, cm);

            new GridDragSource(grid);

            MegaUtil.decoradeGridViewWithAutoHeight(grid, true);

        }
        return grid;
    }

    /**
     * Adds activities to grid
     * 
     * @param result
     */
    public void setActivities(List<SubmissionRevisionDTO> result) {
        grid.getStore().removeAll();
        for (SubmissionRevisionDTO activity : result) {
            grid.getStore().add(beanModelFactory.createModel(activity));
        }
    }

}
